/**
 * Created by admin on 2018/8/14.
 */
//页面基本参数方法和请求
var Page = {
    getUrlParam: function (name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
        var r = window.location.search.substr(1).match(reg);  //匹配目标参数
        if (r != null) return unescape(r[2]);
        return null; //返回参数值
    },
    //定义全局选中学校的pid
    pid: '18',
    //定义分页数据分别对应加入学校和排行榜的分页
    already1: '',
    already2: '',
    //定义分页数据加载更多时的标志 是省/市/区
    scope: '省',
    //事件只执行一次flag
    addFlag: true,
    popFlag: true,
    //ajax省份数据
    ajaxProvince: function () {
        var sessionKey = this.getUrlParam('session-key');
        $.ajax({
            headers: {"session-key": sessionKey},
            url: '/v2/get_province' + window.location.search,
            type: "POST",
            contentType: 'application/json; charset=utf-8',
            dataType: "json",
            data: JSON.stringify({}),
            success: function (data) {
                if (data.code == 0) {
                    handFn.getProvince(data.data);
                    //选中广东后不可选
                    $('.province').attr('disabled',true).find('option:contains("广东")').attr('selected',true);
                } else {
                    $.dialog({
                        titleText: "温馨提示",
                        contentHtml: '<p class="tc">' + data.msg + '</p>'
                    })
                }
            }
        })
    },
    //ajax城市数据
    ajaxCity: function (pid) {
        var postData = {"pid": pid};
        var sessionKey = this.getUrlParam('session-key');
        $.ajax({
            headers: {"session-key": sessionKey},
            url: '/v2/get_city' + window.location.search,
            type: "POST",
            contentType: 'application/json; charset=utf-8',
            dataType: "json",
            data: JSON.stringify(postData),
            success: function (data) {
                if (data.code == 0) {
                    handFn.getCity(data.data);
                } else {
                    $.dialog({
                        titleText: "温馨提示",
                        contentHtml: '<p class="tc">' + data.msg + '</p>'
                    })
                }
            }
        })
    },
    //ajax区域数据
    ajaxTown: function (pid) {
        var postData = {"pid": pid};
        var sessionKey = this.getUrlParam('session-key');
        $.ajax({
            headers: {"session-key": sessionKey},
            url: '/v2/get_town' + window.location.search,
            type: "POST",
            contentType: 'application/json; charset=utf-8',
            dataType: "json",
            data: JSON.stringify(postData),
            success: function (data) {
                if (data.code == 0) {
                    handFn.getTown(data.data);
                } else {
                    $.dialog({
                        titleText: "温馨提示",
                        contentHtml: '<p class="tc">' + data.msg + '</p>'
                    })
                }
            }
        })
    },
    //ajax全国学校数据
    ajaxSchool: function(pid,already){
        Page.addFlag = false;
        var postData = {"pid": pid, "already":already};
        var sessionKey = this.getUrlParam('session-key');
        //加载学校数据时区分是全国/省/市/区4种类型的加载
        var url = '/v2/get_school'; //默认全国
        switch(Page.scope){
            case '省': url = '/v2/get_province_school'; break;
            case '市': url = '/v2/get_city_school'; break;
            case '区': url = '/v2/get_town_school'; break;
        }
        $.ajax({
            headers: {"session-key": sessionKey},
            url: url + window.location.search,
            type: "POST",
            contentType: 'application/json; charset=utf-8',
            dataType: "json",
            data: JSON.stringify(postData),
            success: function (data) {
                if (data.code == 0) {
                    handFn.getSchoolList(data.data.list);
                    Page.already1 = data.data.already;
                    //用户已加入隐藏加入btn
                    if(data.data.my_school.id){
                        $('.btn-join').css({opacity:0,zIndex:-9999});
                    }
                } else {
                    $.dialog({
                        titleText: "温馨提示",
                        contentHtml: '<p class="tc">' + data.msg + '</p>'
                    })
                }
            }
        })
    },
   //ajax学校排行榜
    ajaxSchoolPop: function(){
        var postData = {"pid":"18","already":""};
        var sessionKey = this.getUrlParam('session-key');
        $.ajax({
            headers: {"session-key": sessionKey},
            url: '/v2/get_province_school' + window.location.search,
            type: "POST",
            contentType: 'application/json; charset=utf-8',
            dataType: "json",
            data: JSON.stringify(postData),
            success: function (data) {
                if (data.code == 0) {
                    handFn.getSchoolPop(data.data);
                    Page.already2 = data.data.already;
                } else {
                    $.dialog({
                        titleText: "温馨提示",
                        contentHtml: '<p class="tc">' + data.msg + '</p>'
                    })
                }
            }
        })
    },
    //学校列表分页
    ajaxMoreList: function(pid, already){
        var postData = {"pid":pid,"already": already}
        var sessionKey = this.getUrlParam('session-key');
        //加载更多数据时区分是全国/省/市/区4种类型的加载
        var url = '/v2/get_school'; //默认全国
        switch(Page.scope){
            case '省': url = '/v2/get_province_school'; break;
            case '市': url = '/v2/get_city_school'; break;
            case '区': url = '/v2/get_town_school'; break;
        }
        $.ajax({
            headers: {"session-key": sessionKey},
            url: url + window.location.search,
            type: "POST",
            contentType: 'application/json; charset=utf-8',
            dataType: "json",
            data: JSON.stringify(postData),
            success: function (data) {
                if (data.code == 0) {
                    if(data.data.list != 0){
                        handFn.addSize(data.data.list)
                        Page.already1 = data.data.already;
                        if(data.data.my_school.id){
                            $('.btn-join').css({opacity:0,zIndex:-9999});
                        }
                    }
                } else {
                    $.dialog({
                        titleText: "温馨提示",
                        contentHtml: '<p class="tc">' + data.msg + '</p>'
                    })
                }
            }
        })
    },
    //排行榜列表分页
    ajaxPopList: function(pid,already){
        var postData = {"pid":pid,"already": already}
        var sessionKey = this.getUrlParam('session-key');
        $.ajax({
            url: '/v2/get_province_school' + window.location.search,
            headers: {"session-key": sessionKey},
            type: "POST",
            contentType: 'application/json; charset=utf-8',
            dataType: "json",
            data: JSON.stringify(postData),
            success: function (data) {
                if (data.code == 0) {
                    if(data.data.list != 0) {
                        handFn.popSize(data.data.list)
                        Page.already2 = data.data.already;
                    }
                } else {
                    $.dialog({
                        titleText: "温馨提示",
                        contentHtml: '<p class="tc">' + data.msg + '</p>'
                    })
                }
            }
        })
    },
    //ajax加入学校
    ajaxAddScholl: function(school_id){
        var postData = {"school_id": school_id};
        var sessionKey = this.getUrlParam('session-key');
        $.ajax({
            headers: {"session-key": sessionKey},
            url: '/v2/add_school' + window.location.search,
            type: "POST",
            contentType: 'application/json; charset=utf-8',
            dataType: "json",
            data: JSON.stringify(postData),
            success: function (data) {
                if (data.code == 0) {
                    //加入成功后刷新排行榜
                    Page.ajaxSchoolPop();
                    //用户已加入隐藏加入btn
                    $('.btn-join').css({opacity:0,zIndex:-9999});
                    //加入成功后群聊
                     window.location.href = "cnj://native/chat?groupId="+ data.data.id +"&groupName="+ data.data.name; 
                } else {
                    $.dialog({
                        titleText: "温馨提示",
                        contentHtml: '<p class="tc">' + data.msg + '</p>'
                    })
                }
            }
        })
    },
    //ajax分享页
    ajaxShare: function(){
         var sessionKey = this.getUrlParam('session-key');
        $.ajax({
            headers: {"session-key": sessionKey},
            url: '/v2/get_share' + window.location.search,
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            data: JSON.stringify({}),
            success: function(data){
                if (data.code == 0) {
                    if(!data.data){  //对象为空时
                        $.dialog({
                            titleText: "温馨提示",
                            contentHtml: '<p class="tc">您好，您还未加入学校</p>'
                        })
                    }else {
                        handFn.getShare(data.data);
                    }
                } else {
                    $.dialog({
                        titleText: "温馨提示",
                        contentHtml: '<p class="tc">' + data.msg + '</p>'
                    })
                }
            }
        })
    },
    //集结群聊
    ajaxAddGroup: function(){
        var sessionKey = this.getUrlParam('session-key');
        $.ajax({
            headers: {"session-key": sessionKey},
            url: '/v2/add_mass_group' + window.location.search,
            type: "POST",
            contentType: 'application/json; charset=utf-8',
            dataType: "json",
            data: JSON.stringify({}),
            success: function (data) {
                if (data.code == 0) {
                    //集结成功后群聊
                    window.location.href = "cnj://native/chat?groupId="+ data.data.id +"&groupName="+ data.data.name; 
                } else {
                    $.dialog({
                        titleText: "温馨提示",
                        contentHtml: '<p class="tc">' + data.msg + '</p>'
                    })
                }
            }
        })
    }
};

//事件处理方法
var handFn = {
    //省数据渲染
   getProvince: function(data){
        //清空已有市区数据
        $('.city').html('<option>市</option>');
        $('.town').html('<option>区</option>');
        var str = '<option>省份</option>';
        for(var i in data){
            str += '<option value="'+ data[i].name+'" pid="'+ data[i].id +'">'+ data[i].name +'</option>';
        }
       $('.province').html(str);
    },
    //市数据渲染
   getCity: function(data){
        //清空已有区数据
        $('.town').html('<option>区</option>')
        var str = '<option>市</option>';
        for(var i in data){
            str += '<option value="'+ data[i].name+'" pid="'+ data[i].id +'">'+ data[i].name +'</option>';
        }
        $('.city').html(str);
    },
    //区数据渲染
   getTown: function(data){
       var str = '<option>区</option>';
        for(var i in data){
            str += '<option value="'+ data[i].name+'" pid="'+ data[i].id +'">'+ data[i].name +'</option>';
        }
        $('.town').html(str);
    },
    //学校数据渲染
    getSchoolList: function(data){
        var str = '';
        for(var i in data){
            str += '<li class="flex"><img src="img/join_tx.png"><p><strong>'+ data[i].name.substring(0,20) +'</strong>全'+ Page.scope +'排名'+ data[i].rank +'位</p><a class="btn-join" href="javascript:Page.ajaxAddScholl('+ data[i].id +');">加入</a></li>';
        }
        $('.school-list').html(str);
        Page.addFlag = true;
    },
    //排行榜数据
    getSchoolPop: function(data){
        var arr = data.list;
        //排行列表
        var arrTop = arr.slice(0,3);  //前三名
        $('.school-pop .top-three li.p2').html('<img src="img/tx.png"><p>战力:'+  arrTop[1].power +'<strong>'+ arrTop[1].name +'</strong></p>');
        $('.school-pop .top-three li.p1').html('<img src="img/tx.png"><p>战力:'+  arrTop[0].power +'<strong>'+ arrTop[0].name +'</strong></p>');
        $('.school-pop .top-three li.p3').html('<img src="img/tx.png"><p>战力:'+  arrTop[2].power +'<strong>'+ arrTop[2].name +'</strong></p>');
        // var str = '';
        // for(var i=3; i<arr.length; i++){
        //     str += '<li class="flex"><i class="num">'+ arr[i].rank +'</i><img src="img/join_tx.png"><p class="xx">'+ arr[i].name +'</p><p class="zl">战力 '+ arr[i].power +'</p></li>';
        // }
        // $('.school-pop .list ul').html(str);

        //已加入学校
        var self = data.my_school;
        console.log(self);
        if(self.id){
            $('.school-pop .self').show();
            $('.school-pop .self li').html('<i class="num">我</i><img class="self-tx" src="img/tx.png"><p class="xx">'+ self.name +' <i>第'+ self.rank +'名</i></p><p class="zl">战力 '+ self.power +'</p>');
        }else {
           $('.school-pop .self').hide();
        }
        
    },
    //加入分页列表
    addSize: function(data){
        var str = '';
        for(var i in data){
            str += '<li class="flex"><img src="img/join_tx.png"><p><strong>'+ data[i].name.substring(0,20) +'</strong>全'+ Page.scope +'排名'+ data[i].rank +'位</p><a class="btn-join" href="javascript:Page.ajaxAddScholl('+ data[i].id +');">加入</a></li>';
        }
        $('.school-list').append(str);
        Page.addFlag = true;
    },
    //排行榜分页
    popSize: function(arr){
        var str = '';
        for(var i=0; i<arr.length; i++){
            str += '<li class="flex"><i class="num">'+ arr[i].rank +'</i><img src="img/join_tx.png"><p class="xx">'+ arr[i].name +'</p><p class="zl">战力 '+ arr[i].power +'</p></li>';
        }
        $('.school-pop .list ul').append(str);
        Page.popFlag = true;
    },
    //分享数据渲染
    getShare: function(data){
        $('.school span').text(data.school_name);
        $('.school strong').text(data.school_power);
        $('.pop .num strong').text(data.rank);
        $('.pop .defeat strong').text(data.percent);
        $('.info .town').text(data.town_name);
        $('.info .num').text(data.town_rank);
        $('.user-name').text(data.name);
        $('.user-power').text(data.power);
        $('.user-tx').attr('src', data.avatar)
        //样式自适应
        if(data.school_name.length>5){
            $('.school span').addClass('s');
        }
    }
};

 //用户事件处理
function pageSchool(){
    //切换省份
    $('.province').on('change',function(){
        //清空学校数据及更多数据分页
        $('.school-list').empty();
        Page.already1 = '';
       //判断是否选中还是默认的第一项 如果存在就加载对应省份数据显示出市，否则加载全国数据，市 区全部清空
       var pid = $(this).find('option:selected').attr('pid');
       if(pid) {
          Page.pid = pid;
          Page.scope = '省';
          Page.ajaxCity(Page.pid);
       }else {
         Page.scope = '国';  
       } 
       Page.ajaxSchool(Page.pid, '');
    });

    //切换市
    $('.city').on('change',function(){
        //清空学校数据及更多数据分页
        $('.school-list').empty();
        Page.already1 = '';
        //判断是否选中还是默认的第一项 如果存在就加载对应市据显示出市，否则加载全省数据， 区全部清空
        var pid = $(this).find('option:selected').attr('pid');
        if(pid){
            Page.pid = pid;
            Page.scope = '市';
            Page.ajaxTown(Page.pid);
        }else {
            Page.pid = $('.province').find('option:selected').attr('pid');
            Page.scope = '省';
        }
        Page.ajaxSchool(Page.pid, '');
    })

    //切换区
    $('.town').on('change',function(){
        //清空学校数据及更多数据分页
        $('.school-list').empty();
        Page.already1 = '';
        //判断是否选中还是默认的第一项 如果存在就加载对应市据显示出区，否则加载全市数据， 区全部清空，市如果没有则到省，省没有就是全国
        var pid = $(this).find('option:selected').attr('pid');
        if(pid){
            Page.pid = pid;
            Page.scope = '区';
        }else {
            var citypid = $('.city').find('option:selected').attr('pid');
            if(citypid){
                Page.pid = citypid;
                Page.scope = '市';
            }else {
                Page.pid = $('.province').find('option:selected').attr('pid');
                Page.scope = '省';
            }
           
        }
        Page.ajaxSchool(Page.pid, '');
    })

      //页面初始化时获取省份数据 北京学校数据 排行榜
      // Page.ajaxProvince();
      // Page.ajaxSchool('','');
      // Page.ajaxSchoolPop();

        //只显示出广东数据
        //  Page.ajaxProvince();
         Page.ajaxCity(18);
         Page.ajaxSchool(18, '');
         Page.ajaxSchoolPop();
       

      // $('.btn-share').attr('href', 'share.htm' +  window.location.search);

        //学校滚动数据加载
        $('.join-list .list').scroll(function(){
            var scrollTop = $(this).scrollTop();
            var divHeight = $(this).height();
            var scrollHeight = $('.school-list').height();
            if(scrollTop + divHeight >= scrollHeight){
                 //加载更多数据
                if(Page.addFlag){
                    Page.addFlag = false;
                    Page.ajaxMoreList(Page.pid,Page.already1);
                }
            }
        });
        // //排行版滚动数据加载
        // $('.school-pop').scroll(function(){
        //     var scrollTop = $(this).scrollTop();
        //     var divHeight = $(this).height();
        //     var scrollHeight = $('.shool-pop-box').height();
        //     if(scrollTop + divHeight >= scrollHeight){
        //           if(Page.popFlag){
        //                 Page.popFlag = false;
        //                 Page.ajaxPopList(Page.already2);
        //           }
        //     }
        // });

         //页签切换
        $('.mod-main .tit a').on('touchend',function(){
            $(this).addClass('on').siblings().removeClass('on');
            $('.mod-main .bdcon').eq($(this).index()).show().siblings().hide();
        })

}

function pageShare(){
    Page.ajaxShare();
}